const http = require("http");
const { createHash } = require("crypto");
const fs = require("fs");

const server = http.createServer((req, res) => {
    /* 协商缓存 */

    // 创建etag
    const buffer = fs.readFileSync("./index.html"); // 二进制流文件
    const hashTool = createHash("md5");
    hashTool.update(buffer, "utf-8");
    const etag = hashTool.digest("hex"); //生成md5加密的唯一标识
    const requestEtag = req.headers["if-none-match"];

    const info = fs.statSync("./index.html");

    const requestLastModifyTime = req.headers["if-modified-since"];

    const lastModifyTime = info.mtime.toUTCString();

    if ((requestLastModifyTime && requestLastModifyTime === lastModifyTime) || (requestEtag && requestEtag === etag)) {
        console.log("catch!");
        res.statusCode = 304;
        res.end();
        return;
    }

    console.log("no catch!");
    res.setHeader("last-modified", lastModifyTime);
    res.setHeader("etag", etag);

    /* 强缓存 */
    // const time = new Date(new Date().getTime() + 10 * 1000);

    // res.setHeader("Expires", time.toUTCString());

    // res.setHeader("Cache-Control", "max-age=10000");
    const html = fs.readFileSync("./index.html", "utf-8");
    res.end(html);
});

server.listen(8989);
